require "config/cdr_parser_config.rb"
require "app/helpers/cdr_parser_helper.rb"
require "date"
require "json"



class CdrParserController < ApplicationController
  def start
    iterate_folders(CDR_DATA_FILEROOT)
    
  end
  
  def view1
  end
  
  def iterate_folders(fileroot)
    '''
    It does depth first search for the folder (recursive)
    If a file is a folder, this function calls itself recursively, else parse the file
    '''
    allfiles = Dir[File.join(fileroot, "*")]
    allfiles.each { |i|
      if File.ftype(i) == "directory"
        puts i 
        iterate_folders(i)
      elsif File.ftype(i) == "file" and File.extname(i) == ".CDR" #CDR means that it is a new file
        process_file(i)
        puts i #debug
      end
    }
    end
  end
  
  def process_file(filepath_name)
    puts "I am here process_file with %s" % filepath_name
    cdr_raw_data = get_raw_data(filepath_name)    
    
    # TODO: finish functions here
    #1. cdr_raws
    cdr_raws(cdr_raw_data)
    
    
    File.rename(filepath_name, filepath_name + CDR_NEWEXT)
    
  end
  
  
  ############################################################
  ##
  ## => 0. parsing a file into array of hash
  ##
  ############################################################
  def get_raw_data(filename)
    puts filename
    
    num_debug = 1000
    
    return_array = Array.new
    
    if File.extname(filename) != ".CDR" # This checking is for the case that the shell scripts that generate callcache directly calls this script
      return nil
    end

    infile = File.new(filename, "r")

    count = 0
    for line in infile
      puts line
      values  = line.split(';')
      hash    = Hash.new
      hash[RECORD_ID] = Time.new.to_s #TODO: fix this as file name
        for i in 0...values.size
          hash[KEYS[i]] = values[i].strip # look up the cdr_raw_config file under config folder
          #puts "values %s, %s" % [KEYS[i], values[i]] #XXX debug
        end
      return_array << hash
      count+=1
      break if count>num_debug
    end    
    
    infile.close 
    return return_array
  end
 
  ############################################################
  ##
  ## => 1. update the raw table
  ##
  ############################################################  
  def cdr_raws(cdr_raw_data)
    @debug = ""
    if cdr_raw_data == nil or cdr_raw_data.size==0
      puts "****OH NO IS CDR_RAW_DATA NULL?" 
      return false
    end
    
    for r in cdr_raw_data
      puts r[C3_CALL_DURATION] #XXX debug
      raw = CdrRaw.find_by_record_id(r[RECORD_ID])
      if raw == nil
        raw = CdrRaw.new
        #raw.XXX = r[XXX]
        raw.c1_start_time                            = r[C1_START_TIME]
        puts = r[C1_START_TIME]
        raw.c2_start_time                            = r[C2_START_TIME]
        raw.c3_call_duration                         = r[C3_CALL_DURATION]                              
        raw.c4_call_source                           = r[C4_CALL_SOURCE]
        raw.c5_call_source_q931sig_port              = r[C5_CALL_SOURCE_Q931SIG_PORT]
        raw.c6_call_dest                             = r[C6_CALL_DEST]
        raw.c7_field_unused                          = r[C7_FIELD_UNUSED]
        raw.c8_call_source_custid                    = r[C8_CALL_SOURCE_CUSTID]
        raw.c9_called_party_on_dest__CALL_TO_        = r[C9_CALLED_PARTY_ON_DEST__CALL_TO_]
        raw.c10_called_party_from_src                = r[C10_CALLED_PARTY_FROM_SRC]
        raw.c11_call_type                            = r[C11_CALL_TYPE]
        raw.c12_field_unused                         = r[C12_FIELD_UNUSED]
        raw.c13_disconnect_error_type                = r[C13_DISCONNECT_ERROR_TYPE]
        raw.c14_call_error                           = r[C14_CALL_ERROR]
        raw.c15_call_error                           = r[C15_CALL_ERROR]
        raw.c16_field_unused                         = r[C16_FIELD_UNUSED]
        raw.c17_field_unused                         = r[C17_FIELD_UNUSED]
        raw.c18_ani__CALLING_FROM_                   = r[C18_ANI__CALLING_FROM_]
        raw.c19_field_unused                         = r[C19_FIELD_UNUSED]
        raw.c20_field_unused                         = r[C20_FIELD_UNUSED]
        raw.c21_field_unused                         = r[C21_FIELD_UNUSED]
        raw.c22_cdr_seq_no                           = r[C22_CDR_SEQ_NO]
        raw.c23_field_unused                         = r[C23_FIELD_UNUSED]
        raw.c24_callid                               = r[C24_CALLID]
        raw.c25_call_hold_time                       = r[C25_CALL_HOLD_TIME]
        raw.c26_call_source_regid                    = r[C26_CALL_SOURCE_REGID]
        raw.c27_call_source_uport                    = r[C27_CALL_SOURCE_UPORT]
        raw.c28_call_dest_regid                      = r[C28_CALL_DEST_REGID]
        raw.c29_call_dest_uport                      = r[C29_CALL_DEST_UPORT]
        raw.c30_isdn_cause_code                      = r[C30_ISDN_CAUSE_CODE]
        raw.c31_called_party_after_src_calling_plan  = r[C31_CALLED_PARTY_AFTER_SRC_CALLING_PLAN]
        raw.c32_call_error_dest                      = r[C32_CALL_ERROR_DEST]
        raw.c33_call_error_dest                      = r[C33_CALL_ERROR_DEST]
        raw.c34_call_error_event_str                 = r[C34_CALL_ERROR_EVENT_STR]
        raw.c35_new_ani                              = r[C35_NEW_ANI]
        raw.c36_call_duration                        = r[C36_CALL_DURATION]
        raw.c37_incoming_leg_callid                  = r[C37_INCOMING_LEG_CALLID]
        raw.c38_protocol                             = r[C38_PROTOCOL]
        raw.c39_cdr_type                             = r[C39_CDR_TYPE]
        raw.c40_hunting_attempts                     = r[C40_HUNTING_ATTEMPTS]
        raw.c41_caller_trunk_group                   = r[C41_CALLER_TRUNK_GROUP]
        raw.c42_call_pdd                             = r[C42_CALL_PDD]
        raw.c43_h323_dest_ras_error                  = r[C43_H323_DEST_RAS_ERROR]
        raw.c44_h323_dest_h225_error                 = r[C44_H323_DEST_H225_ERROR]
        raw.c45_sip_dest_respcode                    = r[C45_SIP_DEST_RESPCODE]
        raw.c46_dest_trunk_group                     = r[C46_DEST_TRUNK_GROUP]
        raw.c47_call_duration_fractional             = r[C47_CALL_DURATION_FRACTIONAL]
        raw.c48_timezone                             = r[C48_TIMEZONE]
        raw.c49_msw_name                             = r[C49_MSW_NAME]
        raw.c50_called_party_after_transit_route     = r[C50_CALLED_PARTY_AFTER_TRANSIT_ROUTE]
        raw.c51_called_party_on_dest_num_type        = r[C51_CALLED_PARTY_ON_DEST_NUM_TYPE]
        raw.c52_called_party_from_src_num_type       = r[C52_CALLED_PARTY_FROM_SRC_NUM_TYPE]
        raw.c53_call_source_realm_name               = r[C53_CALL_SOURCE_REALM_NAME]
        raw.c54_call_dest_realm_name                 = r[C54_CALL_DEST_REALM_NAME]
        raw.c55_call_dest_crname                     = r[C55_CALL_DEST_CRNAME]
        raw.c56_call_dest_custid                     = r[C56_CALL_DEST_CUSTID]
        raw.c57_call_zone_data                       = r[C57_CALL_ZONE_DATA]
        raw.c58_calling_party_on_dest_num_type       = r[C58_CALLING_PARTY_ON_DEST_NUM_TYPE]
        raw.c59_calling_party_from_src_num_type      = r[C59_CALLING_PARTY_FROM_SRC_NUM_TYPE]
        raw.c60_original_isdn_cause_code             = r[C60_ORIGINAL_ISDN_CAUSE_CODE]
        raw.c61_packets_received_on_src_leg          = r[C61_PACKETS_RECEIVED_ON_SRC_LEG]
        raw.c62_packets_lost_on_src_leg              = r[C62_PACKETS_LOST_ON_SRC_LEG]
        raw.c63_packets_discarded_on_src_leg         = r[C63_PACKETS_DISCARDED_ON_SRC_LEG]
        raw.c64_pdv_on_src_leg                       = r[C64_PDV_ON_SRC_LEG]
        raw.c65_codec_on_src_leg                     = r[C65_CODEC_ON_SRC_LEG]
        raw.c66_latency_on_src_leg                   = r[C66_LATENCY_ON_SRC_LEG]
        raw.c67_rfactor_on_src_leg                   = r[C67_RFACTOR_ON_SRC_LEG]
        raw.c68_packets_received_on_dest_leg         = r[C68_PACKETS_RECEIVED_ON_DEST_LEG]
        raw.c69_packets_lost_on_dest_leg             = r[C69_PACKETS_LOST_ON_DEST_LEG]
        raw.c70_packets_discarded_on_dest_leg        = r[C70_PACKETS_DISCARDED_ON_DEST_LEG]
        raw.c71_pdv_on_dest_leg                      = r[C71_PDV_ON_DEST_LEG]
        raw.c72_codec_on_dest_leg                    = r[C72_CODEC_ON_DEST_LEG]
        raw.c73_latency_on_dest_leg                  = r[C73_LATENCY_ON_DEST_LEG]
        
        if r[C74_RFACTOR_ON_DEST_LEG].to_s.size == 0
          raw.c74_rfactor_on_dest_leg = nil
        else
          begin
            i = Integer(r[C74_RFACTOR_ON_DEST_LEG])
            raw.c74_rfactor_on_dest_leg = r[C74_RFACTOR_ON_DEST_LEG]
          rescue
            raw.c74_rfactor_on_dest_leg = nil
          end          
        end        
        raw.c74_rfactor_on_dest_leg                  = r[C74_RFACTOR_ON_DEST_LEG]
        raw.c75_sip_src_respcode                     = r[C75_SIP_SRC_RESPCODE]
        raw.c76_peer_protocol                        = r[C76_PEER_PROTOCOL]
        raw.c77_src_private_ip                       = r[C77_SRC_PRIVATE_IP]
        raw.c78_dest_private_ip                      = r[C78_DEST_PRIVATE_IP]
        raw.c79_src_igrp_name                        = r[C79_SRC_IGRP_NAME]
        raw.c80_dest_igrp_name                       = r[C80_DEST_IGRP_NAME]
        raw.c81_                                     = r[C81_]
        raw.c82_                                     = r[C82_]
        raw.c83_                                     = r[C83_]
        raw.c84_                                     = r[C84_]
        raw.c85_                                     = r[C85_]
        raw.c86_WHO_DISCONNECTED                     = r[C86_WHO_DISCONNECTED]
        raw.c87_                                     = r[C87_]
        raw.c88_                                     = r[C88_]
        raw.c89_                                     = r[C89_]
        raw.c90_                                     = r[C90_]
        raw.c91_                                     = r[C91_]
        raw.c92_                                     = r[C92_]
        raw.c93_                                     = r[C93_]
        raw.c94_                                     = r[C94_]
        raw.c95_                                     = r[C95_]
        raw.c96_                                     = r[C96_]
        raw.c97_                                     = r[C97_]
        raw.c98_                                     = r[C98_]
        raw.c99_                                     = r[C99_]
 
        raw.save!
        
        #puts "%s, %s" % [r[0], r[1]]
        
        #TODO : createview
        
      end
    end    
  end

